﻿using Learun.Application.Scheduler;
using Learun.Application.Web.Common;
using System;
using System.Timers;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.SessionState;

namespace Learun.Application.Web
{
    /// <summary>
    /// 版 本 PIT-ADMS V7.0.3 敏捷开发框架
    /// Copyright (c) 2013-2018 Hexagon PPM
    /// 创建人：研发部
    /// 日 期：2017.03.08
    /// 描 述：应用程序全局设置
    /// </summary>
    public class MvcApplication : HttpApplication
    {
        /// <summary>
        /// 启动应用程序
        /// </summary>
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            //在API启动时注册路由映射
            GlobalConfiguration.Configure(WebApiConfig.Register);
            RouteConfig.RegisterRoutes(RouteTable.Routes);

            ////一天执行一次备份
            Timer timer = new Timer(86400000);
            //timer.Elapsed += Timer_Elapsed;
            //timer.Start();
        }

        private void Timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            ProjectBakupJob.Execute();
        }

        /// <summary>
        /// Session配置之WebApi支持(https://www.cnblogs.com/ca47/p/4603701.html)
        /// </summary>
        public override void Init()
        {
            PostAuthenticateRequest += (s, e) => HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
            base.Init();
        }
        /// <summary>
        /// 应用程序错误处理
        /// </summary>
        /// <param name="sender">sender</param>
        /// <param name="e">EventArgs</param>
        protected void Application_Error(object sender, EventArgs e)
        {
            var lastError = Server.GetLastError();

            ////   在应用程序关闭时运行的代码
            //if (BaseScheduler.scheduler != null)
            //{
            //    BaseScheduler.scheduler.Shutdown(true);
            //}
        }

        protected void Application_End(object sender, EventArgs e)
        {
            //   在应用程序关闭时运行的代码
            if (BaseScheduler.scheduler != null)
            {
                BaseScheduler.scheduler.Shutdown(true);
            }
        }
    }
}
